'use client';

import useDebounceFn from '@/hooks/use-debounce-fn';
import { useToast } from '@/hooks/use-toast';
import { authClient } from '@/lib/auth-client';
import { useSocket } from '@/providers/socket-provider';
import { MESSAGE_EVENT, type Message } from '@/service/type/socket';
import Link from 'next/link';
import { usePathname } from 'next/navigation';
import { useEffect, useRef } from 'react';
import { Button } from '../ui/button';

export default function NewMessageNotify({
  offlineMessage,
}: {
  offlineMessage: {
    userId: string;
    name: string;
  } | null;
}) {
  const { data: session } = authClient.useSession();
  const onceRef = useRef(false);
  const { toast } = useToast();
  const debounceToast = useDebounceFn(toast, 1000);
  const socket = useSocket();
  const pathname = usePathname();

  useEffect(() => {
    if (onceRef.current) return;
    onceRef.current = true;
    offlineMessage?.userId &&
      debounceToast({
        title: '您有新的消息',
        description: `来自 ${offlineMessage.name} 的消息`,
        action: (
          <Link
            href={
              pathname.startsWith('/shop')
                ? `/shop/message/${offlineMessage.userId}`
                : `/message/${offlineMessage.userId}`
            }
          >
            <Button>查看</Button>
          </Link>
        ),
      });
  }, [offlineMessage?.userId, offlineMessage?.name, pathname, debounceToast]);

  useEffect(() => {
    socket?.on(MESSAGE_EVENT, (args: Message) => {
      ![`/message/${args.user.id}`, `/shop/message/${args.user.id}`].includes(
        pathname,
      ) &&
        session?.user.id !== args.user.id &&
        debounceToast({
          title: '您有新的消息',
          description: `来自 ${args.user.name} 的消息`,
          action: (
            <Link
              href={
                pathname.startsWith('/shop')
                  ? `/shop/message/${args.user.id}`
                  : `/message/${args.user.id}`
              }
            >
              <Button>查看</Button>
            </Link>
          ),
        });
    });
    return () => {
      socket?.off(MESSAGE_EVENT);
    };
  }, [socket, debounceToast, pathname, session?.user.id]);

  return null;
}
